package com.hy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.common.base.RespResult;
import com.hy.common.base.RespResultCode;
import com.hy.common.consts.CommonConst;
import com.hy.common.consts.ExcelConstants;
import com.hy.common.consts.RedisConst;
import com.hy.common.excel.EntityExcelImport;
import com.hy.common.exception.ImportException;
import com.hy.common.log.eventbus.*;
import com.hy.common.utils.ExcelUtil;
import com.hy.common.utils.CommonUtils;
import com.hy.entity.dto.*;
import com.hy.entity.pojo.*;
import com.hy.entity.vo.*;
import com.hy.mapper.*;
import com.hy.service.HyPropertyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class HyPropertyServiceImpl implements HyPropertyService {




    @Resource
    private HyPropertyMapper hyPropertyMapper;
    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Resource
    private HyUserMapper userMapper;

    @Resource
    private HyDepartmentMapper departmentMapper;


    @Resource
    private HyPlaceMapper hyPlaceMapper;
    @Resource
    private HyPropertySortMapper sortMapper;
    @Resource
    private HyUnitMapper hyUnitMapper;
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private HyPropertyRecordMapper recordMapper;
    private Authentication authentication;



    @Override
    public Integer getCount(HyPropertySearchDTO searchDTO) {
        authentication= SecurityContextHolder.getContext().getAuthentication();
        HyUserVO principal = (HyUserVO) authentication.getPrincipal();
        List<String> roles = principal.getRoles();
        Integer totalCount=0;
        if(CommonUtils.isMember(roles, CommonConst.SYSTEM_ROLE_NAME)){

            totalCount=hyPropertyMapper.getCountByDto(searchDTO);
        }else if (CommonUtils.isMember(roles,CommonConst.PROPERTIES_ROLE_NAME)||CommonUtils.isMember(roles,CommonConst.UNIT_ROLE_NAME)){
            searchDTO.setUnitId(principal.getUnitId());
            totalCount=hyPropertyMapper.getCountByDto(searchDTO);
        }else {
            searchDTO.setUnitId(principal.getUnitId());
            searchDTO.setUser(principal.getUserId());
            totalCount=hyPropertyMapper.getCountByDto(searchDTO);
        }
        return totalCount;
    }

    @Override
    public RespResult handAdd(HyProperty hyProperty) {
        authentication=SecurityContextHolder.getContext().getAuthentication();
        HyUserVO userVO= (HyUserVO) authentication.getPrincipal();
        List<String> roles = userVO.getRoles();
        RespResult result;
        if (ObjectUtils.isEmpty(hyProperty.getPropertyCode())){
            hyProperty.setPropertyCode(CommonUtils.getPropertyCode(hyProperty,sortMapper.selectById(hyProperty.getPropertyTypeId())));
        }
        Long propertyId=0L;
        Long increment=0L;
        synchronized (RedisConst.lock){
           propertyId = redisTemplate.opsForValue().increment(RedisConst.PROPERTY_INCREMENT_ID);
           increment = redisTemplate.opsForValue().increment(RedisConst.UNIT_INCREMENT_RFID+userVO.getUnitId());
        }

        if (CommonUtils.isMember(roles,CommonConst.SYSTEM_ROLE_NAME)){
            hyProperty.setPropertyId(propertyId.intValue());
            hyProperty.setPropertyRfid(increment.intValue());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(new Date(new Date().getTime() + CommonConst.GMT_TIME));
            hyProperty.setCreateDate(format);
            hyProperty.setUpdateDate(format);
            hyPropertyMapper.insert(hyProperty);
            result =RespResult.getInstance(RespResultCode.Add_SUCCESS);
        }else {
            hyProperty.setPropertyId(propertyId.intValue());
            hyProperty.setPropertyRfid(increment.intValue());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(new Date(new Date().getTime() + CommonConst.GMT_TIME));
            hyProperty.setUnitId(userVO.getUnitId());
            hyProperty.setCreateDate(format);
            hyProperty.setUpdateDate(format);
            hyPropertyMapper.insert(hyProperty);
            result =RespResult.getInstance(RespResultCode.Add_SUCCESS);
        }
        return result;
    }

    @Override
    public RespResult updateProperty(HyProperty hyProperty) {
        authentication=SecurityContextHolder.getContext().getAuthentication();
        HyUserVO userVO= (HyUserVO) authentication.getPrincipal();
        List<String> roles = userVO.getRoles();
        RespResult result;
        if (CommonUtils.isMember(roles,CommonConst.SYSTEM_ROLE_NAME)){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(new Date(new Date().getTime() + CommonConst.GMT_TIME));
            hyProperty.setUpdateDate(format);//暂未进行区域合法性校验
            hyPropertyMapper.updateById(hyProperty);
            result=RespResult.getInstance(RespResultCode.UPDATE_SUCCESS);

        }else {
            hyProperty.setUnitId(userVO.getUnitId());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(new Date(new Date().getTime() + CommonConst.GMT_TIME));
            hyProperty.setUpdateDate(format);//暂未进行区域合法性校验
            hyPropertyMapper.updateById(hyProperty);
            result=RespResult.getInstance(RespResultCode.UPDATE_SUCCESS);

        }

        return result;
    }

    public boolean isCheck(List<Integer> ids){
        authentication= SecurityContextHolder.getContext().getAuthentication();
        HyUserVO currentUserInfo=(HyUserVO)authentication.getPrincipal();
        for (Integer propertyId:ids) {
            HyProperty hyProperty = hyPropertyMapper.selectById(propertyId);
            if (hyProperty.getUnitId()!=currentUserInfo.getUnitId()){
                return false;
            }
        }
        return true;

    };
    @Override
    public RespResult delete(List<Integer> ids) {
        authentication= SecurityContextHolder.getContext().getAuthentication();
        HyUserVO currentUserInfo=(HyUserVO)authentication.getPrincipal();
        List<String> roles = currentUserInfo.getRoles();
        if (CommonUtils.isMember(roles,CommonConst.SYSTEM_ROLE_NAME)){

            hyPropertyMapper.deleteBatchIds(ids);
            return RespResult.getInstance(RespResultCode.DEL_SUCCESS);
        }else {
            if (isCheck(ids)){
                hyPropertyMapper.deleteBatchIds(ids);
                return RespResult.getInstance(RespResultCode.DEL_SUCCESS);
            }else {
                return RespResult.error(500,"你没有删除该资产的权限！");
            }
        }
    }

    @Override
    public RespResult showPropertyDetail() {
        return null;
    }

    @Override
    public List<HyPropertyVO> findList(Map<String, Object> beanToMap) {
        return hyPropertyMapper.findHyPropertyListByMap(beanToMap);
    }

    @Override
    public Integer getTotalCount(Map<String ,Object> queryCondition) {
        authentication= SecurityContextHolder.getContext().getAuthentication();
        HyUserVO principal = (HyUserVO) authentication.getPrincipal();
        List<String> roles = principal.getRoles();
        Integer totalCount=0;
        if(CommonUtils.isMember(roles, CommonConst.SYSTEM_ROLE_NAME)){

            totalCount=hyPropertyMapper.getTotalCount(queryCondition);
        }else {
            queryCondition.replace("unitId",principal.getUnitId());
           totalCount=hyPropertyMapper.getTotalCount(queryCondition);
        }
        return totalCount;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveStuListWithBatch(List<HyProperty> data) {
        /**
         * mybatis提供三种sql执行器，分别是SIMPLE（默认）、REUSE、BATCH
         * SIMPLE	默认执行器， 节约服务器资源	每次都要开关Statement
         * REUSE	提升后端接口处理效率	每次一个新sql都缓存，增大JVM内存压力
         * BATCH	专门用于更新插入操作，效率最快	对select 不适用，另外特殊要求，比如限制一次execteBatch的数量时需要写过滤器定制
         */
        // 打开批处理
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
        /*HyPropertyBatchMapper empBatchMapper = session.getMapper(HyPropertyBatchMapper.class);*/
        for (int i = 0,length = data.size(); i < length; i++) {
            hyPropertyMapper.insert(data.get(i));
//            empBatchMapper.insert(data.get(i));
            //每1000条提交一次防止内存溢出
            if(i % 10000==9999){
                session.commit();
                session.clearCache();
            }
        }
        session.commit();
        session.clearCache();


    }

    @Override
    public List<HyPropertyVO> listPage(Map<String, Object> queryCondition, Integer pageNo, Integer pageSize) {
        Integer offset = (pageNo - 1) * pageSize;
        Integer rows = pageSize;
        authentication= SecurityContextHolder.getContext().getAuthentication();
        HyUserVO principal = (HyUserVO) authentication.getPrincipal();
        List<String> roles = principal.getRoles();
        queryCondition.put("offset",offset);
        queryCondition.put("rows",rows);
        List<HyPropertyVO> hyPropertyVOS=new ArrayList<>();
        if(CommonUtils.isMember(roles, CommonConst.SYSTEM_ROLE_NAME)){

            hyPropertyVOS= hyPropertyMapper.findHyPropertyListByCondition(queryCondition);
        }else {
            queryCondition.put("unitId",principal.getUnitId());
            hyPropertyVOS=hyPropertyMapper.findHyPropertyListByCondition(queryCondition);
        }
        return hyPropertyVOS;
    }

    @Override
    public List<HyPropertyVO> listPageByDto(Map<String, Object> queryCondition, Integer pageNo, Integer pageSize) {
        Integer offset=null;
        Integer rows=null;
        if (pageNo!=null&&pageSize!=null){
           offset = (pageNo - 1) * pageSize;
           rows = pageSize;
        }

        authentication= SecurityContextHolder.getContext().getAuthentication();
        HyUserVO principal = (HyUserVO) authentication.getPrincipal();
        List<String> roles = principal.getRoles();

        queryCondition.put("offset",offset);
        queryCondition.put("rows",rows);
        List<HyPropertyVO> hyPropertyVOS=new ArrayList<>();
        if(CommonUtils.isMember(roles, CommonConst.SYSTEM_ROLE_NAME)){

            hyPropertyVOS= hyPropertyMapper.findHyPropertyListByDto(queryCondition);
        }else if (CommonUtils.isMember(roles,CommonConst.PROPERTIES_ROLE_NAME)||CommonUtils.isMember(roles,CommonConst.UNIT_ROLE_NAME)){
            queryCondition.put("unitId",principal.getUnitId());
            hyPropertyVOS=hyPropertyMapper.findHyPropertyListByDto(queryCondition);
        }else {
            queryCondition.put("user",principal.getUserId());
            queryCondition.put("unitId",principal.getUnitId());
            hyPropertyVOS=hyPropertyMapper.findHyPropertyListByDto(queryCondition);
        }
        return hyPropertyVOS;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespResult importExcelBigData(MultipartFile multipartFile, HttpServletRequest request) {
        try{
            String  lock="property_lock";
        synchronized (lock){
        String redisLock="redis_lock";
        RespResult r = RespResult.success();
        EntityExcelImport excelImport=new EntityExcelImport(this,userMapper,departmentMapper,hyPlaceMapper,sortMapper
        ,hyUnitMapper,hyPropertyMapper);
        excelImport.setLock(lock);
        excelImport.setRedisTemplate(redisTemplate);
        excelImport.setRedisLock(redisLock);

            Integer count=0;
            Integer i=0;

            long start = System.currentTimeMillis();
            Integer sheetNo = Convert.toInt(request.getParameter("sheetNo"), 0);
            ExcelUtil.readExcel(multipartFile.getInputStream(), HyPropertyReadVO.class,
                    excelImport, sheetNo);

            lock.wait();
            count  = excelImport.getRunTimes();
            i = excelImport.getCount().get();
            if (!i.equals(count)) throw new ImportException("参数有误！");
            System.out.println(11);
            log.info("本次导入100w数据，总耗时:{}ms", (System.currentTimeMillis() -start));
            r.setCode(200);
            r.setMessage("导入成功");
            return r;  }
        } catch (Exception e){
            log.error(e.getMessage(), e);
            return RespResult.error(500,e.getMessage());
        }
    }

    @Override
    public void downloadTemplate(HttpServletResponse response) {
        response.setContentType("application/text;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        try (ServletOutputStream outputStream = response.getOutputStream()) {

            /*
			这里要使用ResourceUtils来获取到我们项目的根目录
			不能使用request.getServletContext().getRealPath("/")，这里获取的是临时文件的根目录（所以不能使用这个）
			*/
//                  String path = ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX).getPath();

            ClassPathResource classPathResource = new ClassPathResource(ExcelConstants.FILE_URL);

//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            String format = simpleDateFormat.format(new Date());
//            /*   path = path.substring(1, path.length());*/
//            String realPath = path + ExcelConstants.FILE_URL;
//            System.out.println("路径"+realPath);
//            System.out.println("路径2"+classPathResource.getPath());
            if (!classPathResource.exists()) {
                response.setContentType("text/html;charset=utf-8");
                //response.getWriter().write(str);这种写入的就相当于生成了jsp/html，返回html/jsp，所以需要我们进行contentType的设置
                response.getWriter().write("下载的文件不存在");
                return;
            }

            InputStream in = classPathResource.getInputStream();


            //byte[] b = new byte[in.available()];创建一个输入流大小的字节数组，然后把输入流中所有的数据都写入到数组中
            byte[] b = new byte[1024];
            //文件大小
            //下载形式，一般跟application/octet-stream一起使用
            String realName="资产导入模板.xlsx";
            String percentEncodedFileName = null;
            try {
                percentEncodedFileName = URLEncoder.encode(realName, "utf-8")
                        .replaceAll("\\+", "%20");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

           // 组装contentDisposition的值
            StringBuilder contentDispositionValue = new StringBuilder();
            contentDispositionValue.append("attachment; filename=")
                    .append(percentEncodedFileName);
            response.setHeader("Content-disposition",contentDispositionValue.toString());
            //如果单纯写这个也可以进行下载功能，表示以二进制流的形式
            response.setContentType("application/octet-stream");
//            response.addHeader("Content-Length", "" + 1024*11);
            int read;
            while ((read = in.read(b))!=-1) {
                outputStream.write(b);
            }
            outputStream.close();
            outputStream.flush();

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespResult changeUser(PropertyUserChangeDTO dto) {
        ////资产状态 1：在用、2：待修、3：在修、4：备用、5：闲置、6：调剂、7：待报废、8：报废
        authentication =SecurityContextHolder.getContext().getAuthentication();
        HyUserVO hyUserVO= (HyUserVO) authentication.getPrincipal();
        //先判断该资产是不是这个人的。
        HyProperty hyProperty = hyPropertyMapper.selectById(dto.getPropertyId());
        if (hyProperty.getOwnerId().equals(hyUserVO.getUserId())){
            //1.将该资产的状态设置为审核中、设置更新时间
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String format = simpleDateFormat.format(new Date(new Date().getTime() + CommonConst.GMT_TIME));
            hyProperty.setUpdateDate(format);
            hyProperty.setPropertyState(CommonConst.PROPERTY_ADJUST.byteValue());
            hyPropertyMapper.updateById(hyProperty);
            HyPropertyRecord record=new HyPropertyRecord();
            HyUser  checker=null;

            //2.将该条变更记录插入到 记录表 。 设置状态为待审核。
            if (dto.getCheck()==null||dto.getCheck().equals(1)){
                HyDepartment department = departmentMapper.selectById(hyProperty.getManagerDeptId());
                checker= userMapper.selectById(department.getManagerId());
                record.setCheckerId(department.getManagerId());
                record.setCheckerName(checker.getUsername());

            }else{
                checker=userMapper.selectById(dto.getOwnerId());
                record.setCheckerId(checker.getUserId());
                record.setCheckerName(checker.getUsername());
            }
            record.setPropertyId(hyProperty.getPropertyId());
            record.setDel(1);
            record.setAfterUserId(dto.getOwnerId());
            record.setBeforeUserId(hyUserVO.getUserId());
            record.setPropertyName(hyProperty.getPropertyName());
            record.setRecordState(CommonConst.RECORD_CHECKING);
            record.setCreateDate(format);
            HyUser hyUser = userMapper.selectById(dto.getOwnerId());
            record.setAfterUsername(hyUser.getUsername());
            record.setBeforeUsername(hyUserVO.getUsername());
            record.setUnitId(hyProperty.getUnitId());
            recordMapper.insert(record);
            SmsMsgSendDTO sendDTO = SmsMsgSendDTO.builder().propertyName(hyProperty.getPropertyName())
                    .phone(checker.getPhone())
                    .propertyCode(hyProperty.getPropertyCode())
                    .receiver(record.getAfterUsername())
                    .sender(hyUserVO.getUsername())
                    .time(format)
                    .initiator(hyUserVO.getUsername())
                    .build();
            // 发布异步事件
            EventBusFactory.build().registerAsyncEvent(SmsSendListener.class);
            EventBusFactory.build().postAsyncEvent(SmsEvent.builder().receiveDTO(null).smsMsgSendDTO(sendDTO).eventName("发送短信").build());
            return RespResult.success();
        }


        return RespResult.error(500,"失败！");
    }

    @Override
    public RespResult checkMsg(Integer recordId) {

        authentication =SecurityContextHolder.getContext().getAuthentication();
        HyUserVO hyUserVO= (HyUserVO) authentication.getPrincipal();
        //先判断该资产的变更审核人是不是这个人的。

        HyPropertyRecord record = recordMapper.selectById(recordId);
        if (record.getCheckerId().equals(hyUserVO.getUserId())){

            HyProperty hyProperty = hyPropertyMapper.selectById(record.getPropertyId());
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            HyUser afterUser = userMapper.selectById(record.getAfterUserId());
            String format = simpleDateFormat.format(new Date(new Date().getTime() + CommonConst.GMT_TIME));
            hyProperty.setOwnerId(record.getAfterUserId());
            hyProperty.setUpdateDate(format);
            hyProperty.setPropertyState(CommonConst.PROPERTY_USING.byteValue());
            hyPropertyMapper.updateById(hyProperty);
            record.setRecordState(CommonConst.RECORD_OVER);
            recordMapper.updateById(record);
            SmsMsgReceiveDTO receiveDTO = SmsMsgReceiveDTO.builder()
                    .confirm(record.getAfterUsername())
                    .sender(record.getBeforeUsername())
                    .propertyCode(hyProperty.getPropertyCode())
                    .propertyName(hyProperty.getPropertyName())
                    .time(format)
                    .phone(afterUser.getPhone())
                    .receiver(record.getAfterUsername()).build();
            EventBusFactory.build().registerAsyncEvent(SmsSendListener.class);
            EventBusFactory.build().postAsyncEvent(SmsEvent.builder().smsMsgSendDTO(null).receiveDTO(receiveDTO).eventName("提醒接收人已确认").build());
            return RespResult.success();
        }

        return RespResult.error(500,"失败！");
    }

    public HyUserVO getUser(){
        return (HyUserVO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
    @Override
    public RespResult getUnitTree() {

        HyUserVO user = getUser();
        List<String> roles = user.getRoles();
        if (CommonUtils.isMember(roles,CommonConst.SYSTEM_ROLE_NAME)){

            return RespResult.success().setMessage("系统管理员无树可查！");

        }else {
            HyUnit hyUnit = hyUnitMapper.selectById(user.getUnitId());
            UserTreeVO userTreeVO=new UserTreeVO();
            userTreeVO.setId(1);
            userTreeVO.setRealId(hyUnit.getUnitId());
            userTreeVO.setLabel(hyUnit.getUnitName());
            LambdaQueryWrapper<HyDepartment> hyDepartmentLambdaQueryWrapper=new LambdaQueryWrapper<>();
            hyDepartmentLambdaQueryWrapper.eq(HyDepartment::getUnitId,hyUnit.getUnitId());

            List<HyDepartment> hyDepartments = departmentMapper.selectList(hyDepartmentLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(hyDepartments)){
                List<UserTreeVO> userTreeVOS=new ArrayList<>();
                int index=10;
                int indexUser=1001;
                for (HyDepartment hyDepartment:hyDepartments) {
                    UserTreeVO userTreeVODept=new UserTreeVO();
                    userTreeVODept.setId(index);
                    userTreeVODept.setRealId(hyDepartment.getDepartmentId());
                    userTreeVODept.setLabel(hyDepartment.getDepartmentName());

                    LambdaQueryWrapper<HyUser> hyUserLambdaQueryWrapper=new LambdaQueryWrapper<>();
                    hyUserLambdaQueryWrapper.eq(HyUser::getUnitId,hyUnit.getUnitId());
                    hyUserLambdaQueryWrapper.eq(HyUser::getDepartmentId,hyDepartment.getDepartmentId());
                    List<HyUser> hyUsers = userMapper.selectList(hyUserLambdaQueryWrapper);
                    List<UserTreeVO> userTreeVOUsers=new ArrayList<>();
                    if (!ObjectUtils.isEmpty(hyUsers)){
                        for (HyUser hyUser:hyUsers) {
                            UserTreeVO userTreeVOUser=new UserTreeVO();
                            userTreeVOUser.setId(indexUser);
                            userTreeVOUser.setRealId(hyUser.getUserId());
                            userTreeVOUser.setLabel(hyUser.getUsername());
                            userTreeVOUsers.add(userTreeVOUser);
                            indexUser++;
                        }
                    }
                    userTreeVODept.setChildren(userTreeVOUsers);
                    userTreeVOS.add(userTreeVODept);
                    index++;

                }
                userTreeVO.setChildren(userTreeVOS);



            }

            return RespResult.success(userTreeVO);
        }


    }

    @Override
    public RespResult sortByManageDept(CheckSortDTO sortDTO) {//通过管理部门来分类。



        return null;
    }

    @Override
    public RespResult sortByPropertySort(CheckSortDTO sortDTO) {//通过 资产类别来分类
        return null;
    }

    @Override
    public RespResult sortByManageUser(CheckSortDTO sortDTO) { //通过 资产管理人来分类
        return null;
    }

    @Override
    public RespResult getPropertyByUserId(PropertyOneDTO userId) {


        HyPropertySearchDTO searchDTO =new HyPropertySearchDTO();

        HyUserVO currentUser = CommonUtils.getCurrentUser();
        searchDTO.setDel(1);
        searchDTO.setOutProperty(1);
        searchDTO.setCurrentPage(userId.getCurrentPage());
        searchDTO.setPageSize(userId.getPageSize());
        searchDTO.setOwnerId(userId.getUserId());
        searchDTO.setUnitId(currentUser.getUnitId());
        List<HyPropertyVO> propertyVOS=listPageByDto(BeanUtil.beanToMap(searchDTO),searchDTO.getCurrentPage(),searchDTO.getPageSize());

        return RespResult.success(propertyVOS).setCount(getCount(searchDTO));




    }

    @Override
    public RespResult printGet(PrinterPropertySearchDto searchDto) {

        Page<HyPropertyVO> page=new Page<>(searchDto.getCurrentPage(),searchDto.getPageSize());
       List<HyPropertyVO> propertyVOS=hyPropertyMapper.getPropertyByDto(page,searchDto);

        return RespResult.success(propertyVOS).setCount(Long.valueOf(page.getTotal()).intValue());
    }

    @Override
    public RespResult getPropertyByPropertyId(Integer id) {


      HyPropertyVO propertyVO=  hyPropertyMapper.getPropertyById(id);

      return RespResult.success(propertyVO);


    }

    @Override
    public RespResult getPropertyByCode(String propertyCode) {

       HyPropertyVO property= hyPropertyMapper.getPropertyByCode(propertyCode);
       return RespResult.success(property);
    }
}
